<?php

namespace app\api\controller\delivery;

use app\api\model\order\Order as OrderModel;
use app\api\controller\Controller;
use app\api\model\store\Clerk;
use app\api\service\pay\PayService;
use app\common\model\app\App as AppModel;
use app\common\model\shopper\Shopper;
use app\api\model\user\User as UserModel;
use app\Request;
use GatewayWorker\Lib\Gateway;

/**
 * 普通订单
 */
class User extends Controller
{

    protected $groupkey = ['g_c_','g_s_'];
    
    public function index()
    {
        $user = $this->getUser();
        $clerk = Clerk::getByUser($user);
        if(!$clerk){
            $clerk = Shopper::shopperDetail($user['user_id']);
            if($clerk){
                $clerk['user_id'] = $user['user_id'];
                $clerk['clerk_id'] = $clerk['id'];
                $clerk['is_shopper'] = 1;
            }

        }else{
            $clerk['is_shopper'] = 0;
        }
        return $this->renderSuccess('', $clerk);
    }

    /**
     * 获取配送员信息
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     */
    public function getShopperInfo()
    {
        $user = $this->getUser();
        $shopper = Shopper::shopperDetail($user['user_id']);
        return $this->renderSuccess('', $shopper);
    }

    /**
     * 修改特殊配送员信息
     * @param Request $request
     * @return \think\response\Json|void
     */
    public function updateShopper(Request  $request){
        $data = $request -> param();
        $UserModel = new UserModel ();
        $update_data = [];
        $user = $this->getUser();
        $clerk = Clerk::getByUser($user); //店员信息
        if(!$clerk){
            $clerk = Shopper::shopperDetail($user['user_id']); //特殊配送员（一秒到家）
            if(isset($data['username']) && $data['username']){
                $update_data['username'] = $data['username'];
            }

            if(isset($data['is_rest']) && $data['is_rest']){
                $update_data['is_rest'] = $data['is_rest'];
            }
            if(isset($data['avatar']) && $data['avatar']){
                $UserModel -> where('user_id',$clerk['uid']) -> update(['avatarUrl' => $data['avatar']]);

            }
            if($update_data){
                (new Shopper()) -> where('id',$clerk['id']) -> update($update_data);
                return $this->renderSuccess('修改成功');
            }
        }else{ //修改门店店员信息
            if(isset($data['username']) && $data['username']){
                $update_data['real_name'] = $data['username'];
            }
            if(isset($data['avatar']) && $data['avatar']){
                $UserModel -> where('user_id',$clerk['user_id']) -> update(['avatarUrl' => $data['avatar']]);
            }

            if(isset($data['is_rest']) && $data['is_rest']){
                $update_data['is_rest'] = $data['is_rest'];
            }

            if($update_data){
                (new Clerk()) -> where('clerk_id',$clerk['clerk_id']) -> update($update_data);
                return $this->renderSuccess('修改成功');
            }
        }


    }


    /**
     * 消息推送 （用于测试）
     * @param $uid
     * @return void
     */
    public function messagePush(){
        Gateway::$registerAddress = '127.0.0.1:1238';

        $msg = '您有新的订单，请及时查收';
        $result_data = [];
        $result_data['msg'] = $msg;
        $result_data['type'] = 'success';
        $result_data_json = json_encode($result_data);
        Shopper::messagePush(101206,$result_data_json);//推送消息

        // 向当前client_id发送数据
//        Gateway::sendToClient($client_id[0],"Hello \r\n");
    }


    /**
     * 绑定client_id, uid
     * @return \think\response\Json
     */
    public function bind(){
        $user = $this->getUser();
        if (empty($user)) return $this->renderError('不能为空');
        Gateway::$registerAddress = '127.0.0.1:1238';
        $data = $this->request->post();
        $type  = $data['type']??1;
        if(!$type){
            return $this->renderError('类型出错');
        }
        $client_id = $data['client_id'];
        if(!$client_id){
            return $this->renderError('client_id不能为空');
        }
        if($type == 1){ //特殊配送员
            $shopper = Shopper::shopperDetail($user['user_id']);
            Gateway::bindUid($client_id, $shopper['id']);
        }else{
            $clerk = Clerk::getByUser($user);
            if(!$clerk){
                $clerk = Shopper::shopperDetail($user['user_id']);
                Gateway::joinGroup($client_id, $this->groupkey[1].$clerk['village_id']); //加入组
            }else{
//                file_put_contents('bind.txt',date('Y-m-d H:i:s') . "\r\n", FILE_APPEND);
//                file_put_contents('bind.txt',var_export($clerk['store_id'],true) . "\r\n", FILE_APPEND);
                Gateway::joinGroup($client_id, $this->groupkey[0].$clerk['store_id']); //加入组
                Gateway::bindUid($client_id, $clerk['clerk_id']);//绑定一个人的client_id
            }
        }
        return $this->renderSuccess('绑定成功');
    }
}
